package com.fezs.web.mvc.handle;

import com.fezs.common.constants.ErrorCode;
import com.fezs.common.exception.ServerException;
import com.fezs.common.model.response.ResultBody;
import com.fezs.message.entity.MsgEntity;
import com.fezs.message.template.MessageTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理未进入Controller方法就异常了的, spring会自动转发到/error
 * 如果以进入Controller方法, 会被GlobalExceptionHandler拦截异常
 *
 * @author zhukai
 * @since 2022/8/19
 */
@Slf4j
@RestController
public class GlobalExceptionController implements ErrorController {

    /**
     * 默认错误
     */
    private static final String PATH_DEFAULT = "/error";

    @Value("${spring.application.name}")
    private String appName;

    @Value("${spring.profiles.active}")
    private String profile;

    @Autowired(required = false)
    private MessageTemplate messageTemplate;

    /**
     * JSON格式错误信息
     */
    @RequestMapping(value = PATH_DEFAULT)
    public ResultBody<?> error(HttpServletRequest request) {
        ServerException ex = new ServerException("系统异常!");
        this.sendWxNotice(request, ex);
        return ResultBody.buildFailResult(ErrorCode.INTERNAL_SERVER_ERROR);
    }

    /**
     * 发送微信消息
     */
    private void sendWxNotice(HttpServletRequest req, Throwable ex) {
        if (messageTemplate != null) {
            String content = MsgEntity.getWebMarkdownMsg(appName, profile, req.getRequestURI(), ex);
            messageTemplate.send(MsgEntity.buildMarkdownMsg(content));
        }
    }
}
